﻿using Seagull.BarTender.Print;
using Shared.Method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tools
{
    public partial class FormPrintLabel : Form
    {
        private string _btwPath = null;
        private string _btwPathTwo = null;
        private string _printerName = null;
        private string _printerNameTwo = null;
        private string _btwQuery = "查询提示1";

        public FormPrintLabel()
        {
            InitializeComponent();
        }

        private void textBoxMacAddr_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                Task.Factory.StartNew(()=>
                {
                    PrintStart();
                });      

                e.Handled = true;
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

        private void PrintStart()
        {
            //打印标签
            MacEnterFalse();

            string productMac = this.textBoxMacAddr.Text;

            if (string.IsNullOrEmpty(productMac))
            {
                MessageBox.Show("MAC地址为空");
                MacFocus();
                return;
            }

            //判断MAC地址是否12位
            if (productMac.Length != 12)
            {
                MessageBox.Show("MAC地址不为12位，请检查MAC地址");
                MacFocus();
                return;
            }

            MacFocus();

            if (string.IsNullOrEmpty(_printerName) == false)
                PrintLabel(productMac, _btwPath, _btwQuery, _printerName);
            if (string.IsNullOrEmpty(_printerNameTwo) == false)
                PrintLabel(productMac, _btwPathTwo, _btwQuery, _printerNameTwo);

        }

        private void MacEnterFalse()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacEnterFalse);
                Invoke(d, null);
            }
            else
            {
                this.textBoxMacAddr.Enabled = false;
            }
        }

        private void MacFocus()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d, null);
            }
            else
            {
                this.textBoxMacAddr.Enabled = true;
                this.textBoxMacAddr.Clear();
                this.textBoxMacAddr.Focus();
            }
        }

        private void PrintLabel(string mac, string btwPath, string btwQuery, string printer)
        {
            if (string.IsNullOrEmpty(btwPath) || File.Exists(btwPath) == false)
            {
                AppendRichTextBox("未能获得打标文件，打印失败！请打开打标软件手动打印！");
                return;
            }


            if (string.IsNullOrEmpty(mac) || string.IsNullOrEmpty(btwQuery))
            {
                MessageBox.Show("MAC或查询代码为空，打印失败");
                AppendRichTextBox("MAC或查询代码为空，打印失败");
                return;
            }

            AppendRichTextBox("开始打印标签……");
            Engine bt = new Engine();

            bt.Start();
            LabelFormatDocument btFormat = bt.Documents.Open(btwPath);
            btFormat.DatabaseConnections.QueryPrompts[btwQuery].Value = mac;
            btFormat.PrintSetup.PrinterName = printer;

            btFormat.Print("标签软件");
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            bt.Stop();

            AppendRichTextBox("标签打印完成");
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }

        //将信息写入信息窗口
        private void AppendRichTextBox(string value, bool hasEnter = true)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string, bool> d = new Action<string, bool>(AppendRichTextBox);
                Invoke(d, new object[] { value, hasEnter });
            }
            else
            {
                if (value == null) return;
                if (this.richTextBoxMsg.TextLength >= 2000)
                    this.richTextBoxMsg.Clear();
                this.richTextBoxMsg.AppendText(value);

                if (hasEnter)
                    this.richTextBoxMsg.AppendText("\n");
            }
        }

        private void FormPrintLabel_Load(object sender, EventArgs e)
        {
            _btwPath = AppSetting.GetValue("BtwPath");
            _btwPathTwo = AppSetting.GetValue("BtwPathTwo");
            _printerName = AppSetting.GetValue("PrinterName");
            _printerNameTwo = AppSetting.GetValue("PrinterNameTwo");

            string query = AppSetting.GetValue("BtwQueryName");
            if (string.IsNullOrEmpty(query) == false) _btwQuery = query;
        }
    }
}
